package com.nervenets.web.controller.handler.user.user;

import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.redis.utils.ISyncExecutor;

import javax.servlet.http.HttpServletRequest;

public class UserWeixinBindHandler extends Handler<UserWeixinBindParams> {
    @Override
    public String handle(UserWeixinBindParams params, HttpServletRequest request) throws Exception {
        User weixinUser = userDao.getUserByWechatId(params.getOpenId());
        if (null != weixinUser && weixinUser.getId() != params.getUserId()) {
            return errorMessage(MessageCode.code_444, "该微信已绑定到其他账号，不能再次绑定");
        }
        return (String) redisSyncLocker.idLock(params.getUserId(), o -> {
            final User user = userDao.findById(params.getUserId(), User.class);
            if (null == user) return errorMessage(MessageCode.code_404);
            user.setWechatId(params.getOpenId());
            user.setUnionId(params.getUnionId());
            if (StringUtils.isEmpty(user.getInfo().getName())) {
                user.getInfo().setName(params.getNickname());
            }
            if (StringUtils.isEmpty(user.getAvatar())) {
                user.setAvatar(params.getHeadImgUrl());
            }
            userDao.saveOrUpdate(user);
            globalService.clearRedisUserStored(user.getId());
            return successMessage(user);
        });
    }

    @Override
    public String result() throws Exception {
        return null;
    }
}
